package com.diao.flink.windowAndTimer;

import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

/**
 * @author: chenzhidiao
 * @date: 2021/2/2 9:06
 * @description: Window的类型
 * @version: 1.0
 */
public class WindowType {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        env.setParallelism(5);

        DataStreamSource<String> dStream = env.socketTextStream("localhost", 9999);

        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMapedStream = dStream.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split(",");
                for (String word : words) {
                    out.collect(Tuple2.of(word, 1));
                }
            }
        });


        //AggregateFunction的三个参数类型：第一个是输入数据的类型，第二个是计数器的类型，第三个是输出结果的类型
        /**
         * TODO 这里根据是否执行keyBy操作，分为 KeyedWindow 和 Non Keyed Window
         */
        flatMapedStream.keyBy(tuple->tuple.f0).window(SlidingProcessingTimeWindows.of(Time.seconds(5),Time.seconds(2)))
                .aggregate(new AggregateFunction<Tuple2<String, Integer>, Long, Long>() {

            //初始化计数器
            @Override
            public Long createAccumulator() {
                return 0L;
            }

            //计数器累加的方法
            @Override
            public Long add(Tuple2<String, Integer> value, Long accumulator) {

                return accumulator + value.f1;
            }

            //获取集合结果
            @Override
            public Long getResult(Long accumulator) {
                return accumulator;
            }

            //聚合的方法
            @Override
            public Long merge(Long a, Long b) {
                return a+b;
            }
        }).print().setParallelism(1);

        env.execute("WordCountByWindow");
    }
}
